var express = require('express');
var router = express.Router();
var formidable = require('formidable');
var path = require('path');
var baseP = path.resolve();
var baseImgUrl = "http://pcb7ukio1.bkt.clouddn.com/";
var fs = require('fs');
var qiniu = require('qiniu');
var Article = require("../models/article");



router.get('/', function(req, res, next) {
  res.render('post', { title: '发表微博'});
});


// 为客户端获取 uploadToken
router.post('/getUploadKey', function(req, res, next) {
    var accessKey = '402YZxjC6iLOTtsVn3OAedKy91Bjc6p11rVJfg6h';
    var secretKey = 'V4duV2LCuVPufV6ffqdCPuageC-DscmywGkSLLup';
    var mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
    var options = {
        scope: 'microblog',
        // expires: 7200,
        // returnBody: '{"data":"http://pcb7ukio1.bkt.clouddn.com/$(key)", "errno":"0"}'
      };
      var putPolicy = new qiniu.rs.PutPolicy(options);
      var uploadToken=putPolicy.uploadToken(mac);
      res.json({ errno: 0, data: uploadToken });
})


// 服务端直传 七牛云
function uploadQiniu(localFile, key, cb) {
    var accessKey = '402YZxjC6iLOTtsVn3OAedKy91Bjc6p11rVJfg6h';
    var secretKey = 'V4duV2LCuVPufV6ffqdCPuageC-DscmywGkSLLup';
    var mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
    var options = { scope: 'microblog' };
    var putPolicy = new qiniu.rs.PutPolicy(options);
    var uploadToken = putPolicy.uploadToken(mac);


    var config = new qiniu.conf.Config();
    // 空间对应的机房
    config.zone = qiniu.zone.Zone_z0;
    var formUploader = new qiniu.form_up.FormUploader(config);
    var putExtra = new qiniu.form_up.PutExtra();
    // 文件上传
    formUploader.putFile(uploadToken, key, localFile, putExtra, function (respErr,
        respBody, respInfo) {
        if (respErr) throw respErr;
        cb && cb(respBody);
    });
}


// 上传图片
router.post('/uploadimg', function (req, res, next) {//对应前端请求的路径，请求方法
    var form = formidable.IncomingForm({
        encoding: 'utf-8',//上传编码
        uploadDir: baseP + "/public/upload/",//上传目录，指的是服务器的路径，如果不存在将会报错。
        keepExtensions: true,//保留后缀
        maxFieldsSize: 5 * 1024 * 1024//byte//最大可上传大小
    });

    var allFile = [];
    var storeName = [];
    form.on('progress', function (bytesReceived, bytesExpected) {//在控制台打印文件上传进度
        var progressInfo = {
            value: bytesReceived,
            total: bytesExpected
        };
        console.log('[progress]: ' + JSON.stringify(progressInfo));
    })
        .on('file', function (filed, file) {
            allFile.push([filed, file]);//收集传过来的所有文件
        })
        .on('end', function () {
            allFile.forEach(function (file, index) {
                var date = new Date();
                var timeStap = Date.parse(date);
                var oldName = file[1].path;
                var newName = form.uploadDir + "/" + timeStap + '_' + file[1].name;
                storeName.push(timeStap + '_' + file[1].name);
                fs.renameSync(oldName, newName);
            });
            // 调用上传七牛云接口
            var localFile = baseP + "/public/upload/" + storeName[0];
            uploadQiniu(localFile, storeName[0], function (data) {
                fs.unlinkSync(localFile);
                res.json({
                    errno: 0,
                    data: [baseImgUrl + data.key] // 返回一个数组，可能是多张图片
                });
            });
            // 多张图片上传处理
            // var dataFile = storeName.map((item) => {
            //     return name = "http://localhost:3003/upload/" + item;
            // })
        })
        .on('error', function (err) {
            console.error('上传失败：', err.message);
            next(err);
        })
        .parse(req, function (err, fields, files) {
            if (err) {
                console.log(err);
            }
        });
});



// 保存微博文章
router.post('/saveAticle', function (req, res, next) {
    // var content = req.body.content;
    // var title = req.body.title;
    // var timeStamp = req.body.timeStamp;
    // var user = req.body.author;
    var cp = req.body;
    Article.create(cp, function (err, con) {
        if (err) {
            console.log("err:", err);
            return next(err);
        }
        res.json({ code: 0, msg: con });
    });
});

module.exports = router;
